# -*- coding: utf-8 -*-
import uuid
from loguru import logger
from webrunnercore import wr #wr模块是webrunner内置的脚本增强sdk
from webrunnercore import *



class 测试负载(WebLoadMachine):
    '''
    用户自定义负载信息
    '''
    负载名称 = '默认负载'

    测试机 = [
        {
            "ip地址": '127.0.0.1',
            "端口": 50000,
            "节点数": 1,
            "主节点": True
        },
    ]

class 测试场景(WebScenario):
    '''
    用户自定义场景信息
    '''
    场景名称 = '默认场景'

    模式 = '梯形负载'
    参数 = {
        '用户数': 50,
        '创建速率': 10,
        '运行时长': 60
    }



class Transaction_Morenfenzu(SerialTransaction):
    '''
    事务定义, 一个事务由多个task构成, 每个task只包含一个请求
    '''

    def __init__(self, parent: "User") -> None:
        super().__init__(parent)
        self.token = None
        self.meeting_id = None
        self.unique_meeting_name = f"test_meeting_{uuid.uuid4().hex[:8]}"

    @property
    def transaction(self):
        # 事务名称
        return "morenfenzu"

    def on_start(self):
        # 事务启动函数
        super().on_start()
    
    def _extract_token_from_login(self, response):
        """从登录响应中提取token"""
        try:
            if response and hasattr(response, 'json'):
                response_data = response.json()
                if response_data.get('code') == 200 and 'data' in response_data:
                    token = response_data['data'].get('token')
                    if token:
                        logger.info(f"成功提取token: {token[:20]}...")
                        return token
            logger.warning("无法从登录响应中提取token")
            return None
        except Exception as e:
            logger.error(f"提取token时发生错误: {e}")
            return None

    def _get_meeting_id_by_name(self, meeting_name):
        """根据会议名称获取会议ID"""
        try:
            url = "http://localhost:8080/api/meetings/list-page"
            headers = {
                'Accept': 'application/json, text/plain, */*',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Host': 'localhost:8080',
                'Referer': 'http://localhost:8080/meeting',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
                'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"'
            }
            if self.token:
                headers['token'] = self.token
            
            params = {
                'meetingName': meeting_name,
                'current': '1',
                'currentUserId': '1',
                'creatPerson': '',
                'startTime': ''
            }
            
            res = self.get(url, headers=headers, params=params, data=None)
            
            if res and hasattr(res, 'json'):
                response_data = res.json()
                if response_data.get('code') == 200 and 'data' in response_data:
                    records = response_data['data'].get('records', [])
                    for record in records:
                        if record.get('meetingName') == meeting_name:
                            meeting_id = record.get('meetingId')
                            if meeting_id:
                                logger.info(f"成功获取会议ID: {meeting_id} (会议名称: {meeting_name})")
                                return meeting_id
                    logger.warning(f"未找到名称为 {meeting_name} 的会议")
                else:
                    logger.warning(f"获取会议列表失败: {response_data}")
            return None
        except Exception as e:
            logger.error(f"获取会议ID时发生错误: {e}")
            return None
    
    @task
    def task_0(self):
        url = "http://localhost:8080/api/user/login"
        headers = {'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Content-Length': '40', 'Content-Type': 'application/json', 'Host': 'localhost:8080', 'Origin': 'http://localhost:8080', 'Referer': 'http://localhost:8080/login', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"'}
        params = {}
        # application/json (dict)
        data = {}
        data['userName'] = 'admin'
        data['password'] = '123456'

        res = self.post(url, headers=headers, params=params, json=data)
        # application/json,res.json()
        
        # 提取token
        self.token = self._extract_token_from_login(res)
        if not self.token:
            logger.error("登录失败，无法获取token，后续操作将被跳过")

    
    @task
    def task_1(self):
        if not self.token:
            logger.warning("跳过创建会议操作：token未获取")
            return
            
        url = "http://localhost:8080/api/meetings/create"
        headers = {'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Content-Length': '254', 'Content-Type': 'application/json', 'Host': 'localhost:8080', 'Origin': 'http://localhost:8080', 'Referer': 'http://localhost:8080/meeting', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'token': self.token}
        params = {}
        params['currentUserId']='1'
        # application/json (dict)
        data = {}
        data['meetingId'] = None
        data['creatPersonId'] = 1
        data['meetingName'] = self.unique_meeting_name
        data['creatPerson'] = '管理员'
        data['startTime'] = '2025-07-29 00:00:00'
        data['endTime'] = '2025-08-08 00:00:00'
        data['meetingCover'] = 'tv.jpg'
        data['meetingCcontent'] = '<p>test</p>'
        data['meetingContent'] = '<p>test</p>'
        data['meetingStatus'] = 0

        logger.info(f"开始创建会议: {self.unique_meeting_name}")
        res = self.post(url, headers=headers, params=params, json=data)
        
        # 检查创建结果
        if res and hasattr(res, 'json'):
            response_data = res.json()
            if response_data.get('code') == 200:
                logger.info(f"会议创建成功: {self.unique_meeting_name}")
                # 获取会议ID
                self.meeting_id = self._get_meeting_id_by_name(self.unique_meeting_name)
                if self.meeting_id:
                    logger.info(f"成功获取会议ID: {self.meeting_id}")
                else:
                    logger.warning("无法获取会议ID，后续更新和删除操作将被跳过")
            else:
                logger.error(f"会议创建失败: {response_data}")
        else:
            logger.error("会议创建请求失败")

    
    @task
    def task_2(self):
        if not self.token:
            logger.warning("跳过查询会议操作：token未获取")
            return
            
        url = "http://localhost:8080/api/meetings/list-page"
        headers = {'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Host': 'localhost:8080', 'Referer': 'http://localhost:8080/meeting', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'token': self.token}
        params = {}
        params['meetingName']=self.unique_meeting_name
        params['current']='1'
        params['currentUserId']='1'
        params['creatPerson']=''
        params['startTime']=''
        # null
        data = None
        res = self.get(url, headers=headers, params=params, data=data)
        # application/json,res.json()

    
    @task
    def task_3(self):
        if not self.token or not self.meeting_id:
            logger.warning("跳过更新会议操作：token或会议ID未获取")
            return
            
        url = "http://localhost:8080/api/meetings/update/true"
        headers = {'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Content-Length': '255', 'Content-Type': 'application/json', 'Host': 'localhost:8080', 'Origin': 'http://localhost:8080', 'Referer': 'http://localhost:8080/meeting', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'token': self.token}
        params = {}
        # application/json (dict)
        data = {}
        data['meetingId'] = self.meeting_id
        data['creatPersonId'] = 1
        data['meetingName'] = f"{self.unique_meeting_name}_updated"
        data['creatPerson'] = '管理员'
        data['startTime'] = '2025-07-29 00:00:00'
        data['endTime'] = '2025-08-08 00:00:00'
        data['meetingCover'] = 'tv.jpg'
        data['meetingCcontent'] = '<p>test1</p>'
        data['meetingContent'] = '<p>test1</p>'
        data['meetingStatus'] = 1

        logger.info(f"开始更新会议: ID={self.meeting_id}")
        res = self.put(url, headers=headers, params=params, json=data)
        # application/json,res.json()

    
    @task
    def task_4(self):
        if not self.token or not self.meeting_id:
            logger.warning("跳过删除会议操作：token或会议ID未获取")
            return
            
        url = "http://localhost:8080/api/meetings/delete"
        headers = {'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Host': 'localhost:8080', 'Origin': 'http://localhost:8080', 'Referer': 'http://localhost:8080/meeting', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'token': self.token}
        params = {}
        params['meetingId']=str(self.meeting_id)
        # null
        data = None
        
        logger.info(f"开始删除会议: ID={self.meeting_id}")
        res = self.delete(url, headers=headers, params=params, data=data)
        # application/json,res.json()


    def on_stop(self):
        # 事务结束函数
        super().on_stop()


class WebrunnerAction(BrowserAction):
    '''
    事务集合, 一个Action包含多个Transaction事务, @task装饰器参数表示事务混合比，
    初始化事务 和 结束事务只执行一次， 执行事务按照混合比执行多次
    '''
    def __init__(self, parent: "User") -> None:
        super().__init__(parent)

    def on_start(self):
        super().on_start()

    @task(1)
    @transaction("morenfenzu")
    def task_morenfenzu(self):
        # 执行事务
        Transaction_Morenfenzu(self).run()

    def on_stop(self):
        super().on_stop()


class WebrunnerUser(CFastHttpUser):
    '''
    虚拟用户, 一个用户循环执行一个Action
    '''
    host = ""
    tasks = [WebrunnerAction]



    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    def on_start(self):
        # 所有虚拟用户创建完成后开始执行，主要用于定义参数化和检查点的策略

        super().on_start()